﻿using System;
using System.Text;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Aspose.Excel;

namespace LenderClearingHouse
{
  public partial class WorkingList : EditablePage
  {
    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      Grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) CheckedProperties.Clear();

        tdClearIcon.Visible = IsEditable();
        tdClear.Visible = IsEditable();
        tdCopyIcon.Visible = IsEditable();
        tdCopy.Visible = IsEditable();
        tdMoveIcon.Visible = IsEditable();
        tdMove.Visible = IsEditable();
              
        listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);
        RadAjaxManager.AjaxSettings.AddAjaxSetting(Grid, Grid);
    }

    static List<long> CheckedProperties
    {
        get
        {
            List<long> result = HttpContext.Current.Session["WorkingListCheckedProperties"] as List<long>;
            if (result == null)
            {
                result = new List<long>();
                HttpContext.Current.Session["WorkingListCheckedProperties"] = result;
            }

            return result;
        }
    }

    protected override void SetupParameters(ParameterCollection coll)
    {
        base.SetupParameters(coll);
        coll.Add(new Parameter("VO"));
        coll.Add(new Parameter("MaxBid"));
        coll.Add(new Parameter("EstVal"));
        coll.Add(new Parameter("Site"));
        coll.Add(new Parameter("OnOff"));
    }

    protected override void CreateColumns(GridColumnCollection columns)
    {
        GridTemplateColumn gtc;
        int newIndex = 3;

        if (IsEditable())
        {
            gtc = new GridTemplateColumn()
            {
                UniqueName = "Checked",
                ItemTemplate = new CheckBoxedColumn("Checked"),
                AllowFiltering = false
            };
            gtc.HeaderStyle.Width = Unit.Pixel(30);
            columns.Add(gtc);

            ++newIndex;
        }
        else
        {
            newIndex = 2;
        }

      base.CreateColumns(columns);

      GridBoundColumn col = new GridBoundColumn();
      col.DataField = "VO";
      col.HeaderText = "v/o";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      /*GridTemplateColumn gtc = new GridTemplateColumn()
      {
          UniqueName = "VO",
          HeaderText = "v/o",
          ItemTemplate = new SpanColumn("VO"),
          EditItemTemplate = new VOColumnEdit("VO"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 1,
          DataField = "VO",
          SortExpression = "VO"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);*/

      gtc = new GridTemplateColumn()
      {
          UniqueName = "MaxBid",
          HeaderText = "MaxBd",
          ItemTemplate = new DollarColumn("MaxBid"),
          EditItemTemplate = new CurrencyColumnEdit("MaxBid"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 2,
          DataField = "MaxBid",
          SortExpression = "MaxBid"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);

      gtc = new GridTemplateColumn()
      {
          UniqueName = "EstVal",
          HeaderText = "EstVal",
          ItemTemplate = new DollarColumn("EstVal"),
          EditItemTemplate = new CurrencyColumnEdit("EstVal"),
          ConvertEmptyStringToNull = false,
          EditFormColumnIndex = 1,
          DataField = "EstVal",
          SortExpression = "EstVal"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "Site";
      col.HeaderText = "Site";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "OnOff";
      col.HeaderText = "On/Off";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);

      Utilities.MoveColumn(columns, "AuctionDate", ref newIndex);
      Utilities.MoveColumn(columns, "Trustee", ref newIndex);
      Utilities.MoveColumn(columns, "TsNumber", ref newIndex);
      Utilities.MoveColumn(columns, "Apn", ref newIndex);
      Utilities.MoveColumn(columns, "PropertyLocation", ref newIndex);
      Utilities.MoveColumn(columns, "ZipCode", ref newIndex);
      Utilities.MoveColumn(columns, "VO", ref newIndex);
      Utilities.MoveColumn(columns, "Stories", ref newIndex);
      Utilities.MoveColumn(columns, "ConstructYear", ref newIndex);
      Utilities.MoveColumn(columns, "TotalSqft", ref newIndex);
      Utilities.MoveColumn(columns, "LotSize", ref newIndex);
      Utilities.MoveColumn(columns, "Bedrooms", ref newIndex);
      Utilities.MoveColumn(columns, "Bathrooms", ref newIndex);
      Utilities.MoveColumn(columns, "GarageSqft", ref newIndex);
      Utilities.MoveColumn(columns, "Pool", ref newIndex);
      Utilities.MoveColumn(columns, "Spa", ref newIndex);
      Utilities.MoveColumn(columns, "EstimatedBid", ref newIndex);
      Utilities.MoveColumn(columns, "TsOpeningBid", ref newIndex);
      Utilities.MoveColumn(columns, "MaxBid", ref newIndex);
      Utilities.MoveColumn(columns, "EstVal", ref newIndex);
      Utilities.MoveColumn(columns, "Nos", ref newIndex);
      Utilities.MoveColumn(columns, "Liens", ref newIndex);
      Utilities.MoveColumn(columns, "Tax", ref newIndex);
      Utilities.MoveColumn(columns, "Site", ref newIndex);
      Utilities.MoveColumn(columns, "OnOff", ref newIndex);
      Utilities.MoveColumn(columns, "MiscNotes", ref newIndex);
      Utilities.MoveColumn(columns, "AssessorDesc", ref newIndex);
      Utilities.MoveColumn(columns, "Hoa", ref newIndex);
      Utilities.MoveColumn(columns, "PrelistStatus", ref newIndex);
      Utilities.MoveColumn(columns, "PurchasePrice", ref newIndex);
      Utilities.MoveColumn(columns, "RehabCosts", ref newIndex);
      Utilities.MoveColumn(columns, "LandUse", ref newIndex);
      Utilities.MoveColumn(columns, "Phase", ref newIndex);
      Utilities.MoveColumn(columns, "ListingStatus", ref newIndex);
      Utilities.MoveColumn(columns, "Client", ref newIndex);
      Utilities.MoveColumn(columns, "CloseDate", ref newIndex);
      Utilities.MoveColumn(columns, "Source", ref newIndex);
      Utilities.MoveColumn(columns, "DateRecorded", ref newIndex);

      columns.Remove(columns.FindByDataField("EscrowCompany"));

      int index = Utilities.GetColumnIndex(columns, "MiscNotes") + 1;
      columns.Insert(index, Utilities.CreateBoundColumn("NdsCorp_SaleDate", "National Default – Sale Date Previous/Projected", true));
      columns.Insert(index, Utilities.CreateBoundColumn("PriorityPost_Status", "Priority Post – Status"));
      columns.Insert(index, Utilities.CreateBoundColumn("LPS_SalesStatus", "LPS - Sales Status"));
      columns.Insert(index, Utilities.CreateTemlateDateColumn("ReconTrust_DateOfSale", "Recon Trust – Date of Sale", 0));
    }
       
    void SearchButton_Click(object sender, ImageClickEventArgs e)
    {
      Grid.Rebind();
      listFilter.ClearFilter();
    }

    protected override string GetPropertyDetailsColumnEditorID()
    {
      return edTextBox.ID;
    }

    protected override Control GetGridContainer()
    {
      return phGrid;
    }

    protected override string GetDataSourceID()
    {
      return sqlDataSource.ID;
    }

    protected void sqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {       
    }

    protected void lnkExportToExcel_Click(object sender, EventArgs e)
    {
      //HideColumn("DeleteButton");
      //HideColumn("EditButton");
      //HideColumn("Address");

      //Grid.MasterTableView.ExportToExcel();

        DataView dv = new DataView();
        DataTable dt = new DataTable();
        dv = sqlDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
        dt = dv.ToTable();

        Excel ex = Utilities.GetExcel();
        Worksheet ws = ex.Worksheets[0];

        int startRow = 0;
        Utilities.GridToExcel(dt, Grid, ws, true, ref startRow);
        ex.Save("WorkingList.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
        HttpContext.Current.Response.End();
    }

    protected void lnkRefreshGrid_Click(object sender, EventArgs e)
    {
      Grid.Rebind();
    }

    protected void lnkClear_Click(object sender, EventArgs e)
    {     
      //Delete Images
      //string[] fileImagePaths = Directory.GetFiles(Server.MapPath("~/DocSecure/PropertyImages/"));
      //foreach (string filePath in fileImagePaths)
      //  File.Delete(filePath);
      ////Delete documents
      //string[] fileDocPaths = Directory.GetFiles(Server.MapPath("~/DocSecure/PropertyDocuments/"));
      //foreach (string filePath in fileDocPaths)
      //  File.Delete(filePath);

      DataAccess da = new DataAccess();
      DataTable ds = da.ExecuteSQL("clearWorkingList");

      // clear files for all the properties that does not exists in master list
      foreach (DataRow dr in ds.Rows)
      {
          string propDir = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());
          Directory.Delete(propDir, true);
      }

      //CountsControl.SetMessage("The Working List and Photos have been deleted.");
      Grid.Rebind();
    }

    protected void lnkCopyNewToWorkingList_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();
      DataTable tbl = da.ExecuteSQL("spCopyToWorkingList @copyNewOnly = 1");
      int rows = Convert.ToInt32(tbl.Rows[0][0]);

      ScriptManager.RegisterStartupScript(this, this.GetType(),
        "key",
        string.Format("alert('{0} properties were copied to working list');", rows), true);

      Grid.Rebind();
    }

    protected void lnkMoveToLvreo_Click(object sender, EventArgs e)
    {
        DataAccess da = new DataAccess();
        string strSQL = string.Format("spMoveFromWorkingToLvreoList @PropertyIDList = '{0}'", string.Join(",", CheckedProperties.ToArray()));
        DataTable tbl = da.ExecuteSQL(strSQL);
        int rows = Convert.ToInt32(tbl.Rows.Count);

        string sbList = "";
        foreach (DataRow dr in tbl.Rows)
        {
          sbList += string.Format("{0}, {1} <br/>", dr["PropertyLocation"].ToString(), dr["ZipCode"].ToString());
        }

        string msgTemp = File.ReadAllText(Server.MapPath("~/Template/PropertyMoveToLVeo.htm"));
        msgTemp = msgTemp.Replace("%PropertyList%", sbList);
      
        DataTable tblVIP = da.ExecuteSQL("getVIPUsers");
        foreach (DataRow dr in tblVIP.Rows)
        {
          if (dr.IsNull("Email"))
            continue;

          string to = dr["Email"].ToString();
          string subject = "Properties moved to LVREO";
          string body = sbList.ToString();
          string msg = msgTemp;
          Utilities.SendMail(to, subject, "", msg, out msg);
        }

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('{0} properties has been moved to LVREO');", rows), true);

        Grid.Rebind();
        CheckedProperties.Clear();
    }

    protected override SqlDataSource GetSqlDataSource()
    {
      return sqlDataSource;
    }

    protected override ListFilterControl GetListFilterControl()
    {
      return listFilter;
    }

    protected override bool IsEditable()
    {
        return (CurrentUser.UserRole != UserRole.InvestorAdmin) && (CurrentUser.UserRole != UserRole.InvestorUser);
    }

    protected override SourcePage GetSourcePage()
    {
      return SourcePage.WorkingList;
    }

    class CheckBoxedColumn : ITemplate
    {
        string columnName;

        public CheckBoxedColumn(string columnName)
        {
            this.columnName = columnName;
        }

        public void InstantiateIn(Control container)
        {
            CheckBox cb = new CheckBox();
            cb.ID = "checkBox";
            cb.AutoPostBack = true;
            cb.DataBinding += new EventHandler(cb_DataBinding);
            cb.CheckedChanged += new EventHandler(cb_CheckedChanged);

            container.Controls.Add(cb);
        }

        void cb_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridDataItem container = (GridDataItem)cb.NamingContainer;
            long propId = (long)container.GetDataKeyValue("PropertyId");

            if (cb.Checked)
            {
                if (!WorkingList.CheckedProperties.Contains(propId))
                    WorkingList.CheckedProperties.Add(propId);
            }
            else
            {
                WorkingList.CheckedProperties.Remove(propId);
            }
        }

        void cb_DataBinding(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridDataItem container = (GridDataItem)cb.NamingContainer;
            long propId = (long)container.GetDataKeyValue("PropertyId");
            cb.Checked = CheckedProperties.Contains(propId);
        }  
    }

    protected void Archive_Click(object sender, EventArgs e)
    {
        DataAccess da = new DataAccess();
        
        DataTable ds = da.ExecuteSQL(string.Format("spWorkingListToArchive @PropertyIDList = '{0}'",
                    string.Join(",", CheckedProperties.ToArray())));

        // clear files for all the properties that does not exists in master list
        foreach (DataRow dr in ds.Rows)
        {
            var path = Server.MapPath("~/PropertiesFiles/Archives/WorkingList/");
            string propDir = Path.Combine(Server.MapPath("~/PropertiesFiles/LVREO/"), dr["Location"].ToString());

            string propDirToAdd = Path.Combine(path, dr["Location"].ToString());

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //if (Directory.Exists(propDir))
                    Directory.Move(propDir, propDirToAdd);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        Response.Redirect("~/WorkingList.aspx");
    }

     

  }
}